# -*- coding: utf-8 -*-

"""剑指 Offer II 033. 变位词组
给定一个字符串数组 strs ，将 变位词 组合在一起。 可以按任意顺序返回结果列表。
注意：若两个字符串中每个字符出现的次数都相同，则称它们互为变位词。

示例 1:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:
输入: strs = [""]
输出: [[""]]

示例 3:
输入: strs = ["a"]
输出: [["a"]]

提示：
1 <= strs.length <= 10^4
0 <= strs[i].length <= 100
strs[i] 仅包含小写字母"""

class Solution:
    """全为小写字母，首先利用数组为每个字符串中的字符出现次数进行桶排序，偏移量为字符ASCII与97的相对值。
    之后对异位词进行分组，维持一个hashdict{arr26:set(anagrams)}，内部之所以用set，是排除回文字符串，按题意，回文字符串不属于异位词"""
    def groupAnagrams(self, strs):
        hashdict = {}
        anagrams_group = []

        for word in strs:
            key = self.count_chr_bucket(word)
            if key in hashdict.keys():
                if word in hashdict[key]:
                    anagrams_group.append([word])
                else:
                    hashdict[key].add(word)
            else:
                hashdict[key] = set([word,])
        
        for anagrams in hashdict.values():
            anagrams_group.append(list(anagrams))
        
        return anagrams_group
    
    def count_chr_bucket(self, word):
        bucket = [0 for _ in range(0, 26)]
        for ch in word:
            bucket[ord(ch)-97] += 1
        return tuple(bucket)
    
    def groupAnagramsPalin(self, strs):
        hashdict = {}
        anagrams_group = []

        for word in strs:
            key = self.count_chr_bucket(word)
            if key in hashdict.keys():
                hashdict[key].append(word)
            else:
                hashdict[key] = [word,]
        
        for anagrams in hashdict.values():
            anagrams_group.append(anagrams)
        
        return anagrams_group


if __name__ == '__main__':
    so = Solution()
    print(so.groupAnagramsPalin(["eat", "tea", "tan", "ate", "nat", "bat"]))
    print(so.groupAnagramsPalin(["", ""]))
    print(so.groupAnagramsPalin(["a"]))
    print(so.groupAnagramsPalin(["abcba", "abcba", "aabbc"]))
